//
//  HearderVC.m
//  YaoHeAPP
//
//  Created by mac on 15/11/20.
//  Copyright (c) 2015年 mac. All rights reserved.
//

#import "HearderVC.h"
#import "Controller.h"
#import "UIButton+WebCache.h"
#import "Masonry.h"
#import "WebVC.h"
#import "HomeTableVC.h"
#import "AddImageBtn.h"
#import "SDCycleScrollView.h"
#import "HeadClass.h"
#import "SVPullToRefresh.h"
#import "Reachability.h"
#import "ShowMessageView.h"
#import "xianhuoVC.h"
#import "Tool.h"
#import "LocationModel.h"
#import "MJExtension.h"
#import "ProvinceModel.h"
#import "RegionButton.h"
#import "SearchAndResultListViewController.h"
#import "TongYong.h"

@interface HearderVC () <SDCycleScrollViewDelegate, UIAlertViewDelegate> {
    AddImageBtn*button1;
    AddImageBtn*button2;
    SDCycleScrollView *cycleScrollView;
    
    HomeTableVC*tableViewRe;
    
    UITableViewHeaderFooterView*header;
    NSArray *_regionArray;                                          // 从后台请求回来的地区数组
    NSMutableArray *_regionButtonArray;                             // 根据_regionArray初始化的按钮数组
    LocationModel *_locationModel;                                  // 全局变量
}

@property (nonatomic, strong) UIImageView *locationImageView;           // 切换定位背景imageView
@property (nonatomic, strong) UIButton *locationButton;                 // 定位按钮

@end

@implementation HearderVC

- (void)viewWillDisappear:(BOOL)animated {
    [super viewWillDisappear:animated];
    [MobClick endLogPageView:@"HearderVC"];
}

- (void)viewWillAppear:(BOOL)animated {
    
    [super viewWillAppear:animated];
    [MobClick beginLogPageView:@"HearderVC"];
    
    Reachability *reach = [Reachability reachabilityWithHostname:@"www.baidu.com"];
    switch ([reach currentReachabilityStatus]) {
        case NotReachable:
        {
            [self addImgBtn];
            [ShowMessageView showMessage:@"你的网络异常,请检查你的网络设置"];
        }
            break;
        case ReachableViaWWAN:
            break;
        case ReachableViaWiFi:
            break;
    }
}
- (void)viewDidLoad {
    [super viewDidLoad];
    self.view.backgroundColor=bgVCcolor;
    
    width=self.view.frame.size.width;
    height=self.view.frame.size.height;
    self.navigationController.navigationBarHidden=YES;
    
    //加一个导航条
    UIView*navcBar=[[UIView alloc]init];
    navcBar.backgroundColor=[UIColor colorWithRed:90.f/255.f green:191.f/255.f blue:219.f/255.f alpha:1];
    [self.view addSubview:navcBar];
    [self.view bringSubviewToFront:navcBar];
    [navcBar mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.offset(0);   make.left.offset(0);
        make.height.offset(kNavigationBarHeight);  make.right.offset(0);
    }];
    //导航条标题
    UILabel*titleLabel=[[UILabel alloc]init];
    titleLabel.text = @"首页";
    titleLabel.font=Font(17);
    titleLabel.textAlignment=NSTextAlignmentCenter;
    titleLabel.textColor=[UIColor whiteColor];
    [navcBar addSubview:titleLabel];
    [titleLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.offset(25);
        make.left.offset(width/2-50);
        make.width.offset(100);
        make.height.offset(30);
    }];
    
    // 定位按钮
    NSString *lastLocationProvinceNameString = [[NSUserDefaults standardUserDefaults] objectForKey:kProvinceName];
    UIButton *locationButton = [UIButton buttonWithType:UIButtonTypeCustom];
    if (lastLocationProvinceNameString) {
        [locationButton setTitle:lastLocationProvinceNameString forState:UIControlStateNormal];
    } else {
        [locationButton setTitle:@"全国" forState:UIControlStateNormal];
    }
    UIImage *xiaosanjiaoxingImage = [UIImage imageNamed:@"whitearrow_down"];
    [locationButton setImage:xiaosanjiaoxingImage forState:UIControlStateNormal];
    [locationButton setImage:xiaosanjiaoxingImage forState:UIControlStateHighlighted];
    [locationButton setTitleEdgeInsets:UIEdgeInsetsMake(0, 0, 0, 20)];
    [locationButton setImageEdgeInsets:UIEdgeInsetsMake(0, 60, 0, 0)];
    locationButton.titleLabel.font = Font(17);
    [locationButton addTarget:self action:@selector(changeRegion:) forControlEvents:UIControlEventTouchUpInside];
    locationButton.enabled = NO;
    [navcBar addSubview:locationButton];
    [locationButton mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.offset(0);
        make.width.offset(80);
        make.height.offset(28);
        make.bottom.offset(-10);
    }];
    self.locationButton = locationButton;
    
    // 搜索按钮
    UIButton *rightButton = [UIButton buttonWithType:UIButtonTypeCustom];
    [rightButton setBackgroundImage:[UIImage imageNamed:@"icon_homePage_search"] forState:UIControlStateNormal];
    [rightButton addTarget:self action:@selector(searchBuXiuGang) forControlEvents:UIControlEventTouchUpInside];
    [navcBar addSubview:rightButton];
    [rightButton mas_makeConstraints:^(MASConstraintMaker *make) {
        make.right.offset(-15);
        make.width.offset(20);
        make.height.offset(20);
        make.bottom.offset(-14);
    }];
    
    
    //布局界面
    _allData = [[NSMutableDictionary alloc] init];
    //推荐的
    _banner = [[NSMutableArray alloc] init];
    //热点
    _hotArray =[[NSMutableArray alloc] init];
    ImgAry = [[NSMutableArray alloc] init];
    _regionArray = [NSArray array];
    _regionButtonArray = [NSMutableArray array];
    
    //创建表格
    _tableView=[[UITableView alloc]initWithFrame:CGRectMake(0, kNavigationBarHeight, width, height-kNavigationBarHeight-kTabBarHeight) style:UITableViewStylePlain];
    _tableView.dataSource=self;
    _tableView.delegate=self;
    _tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    [self.view addSubview:_tableView];

    //头部滑动广告
    cycleScrollView = [SDCycleScrollView cycleScrollViewWithFrame:CGRectMake(0, 0, width, width/2.6) imageURLStringsGroup:ImgAry];
    cycleScrollView.pageControlAliment = SDCycleScrollViewPageContolAlimentCenter;
    cycleScrollView.delegate = self;
    //cycleScrollView2.titlesGroup = titles;
    cycleScrollView.dotColor = [UIColor whiteColor]; // 自定义分页控件小圆标颜色
    cycleScrollView.autoScrollTimeInterval=4.0;
    

    //刷新数据
    //放置下拉上拉刷新控件
    __weak HearderVC *weakSelf = self;
    [_tableView addPullToRefreshWithActionHandler:^{
        NSString *provinceId = [[NSUserDefaults standardUserDefaults] objectForKey:kLocationRegion];
        [weakSelf loadNewData:provinceId];
    }];
    
    // 请求定位数据
    [self askForLocation];
}

#pragma mark 点击切换地区按钮
- (void)changeRegion:(UIButton *)button {
    UIView *tempSuperView = self.locationImageView.superview;
    if (tempSuperView) {
        [self.locationImageView removeFromSuperview];
    } else {
        self.locationImageView.frame = CGRectMake(12, self.locationButton.bottom-2, 100, 30*_regionArray.count);
        [self.view addSubview:self.locationImageView];
        [self.view bringSubviewToFront:self.locationImageView];
    
        // 区别两种字体颜色
        for (RegionButton *regionButton in _regionButtonArray) {
            if ([self.locationButton.titleLabel.text isEqualToString:regionButton.provinceModel.province_name]) {
                [regionButton setTitleColor:RGBCOLOR(90, 191, 219) forState:UIControlStateNormal];
            } else {
                [regionButton setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
            }
        }
    }
}

#pragma mark 请求定位数据
- (void)askForLocation {
    NSDictionary *paramsDictionary = [NSDictionary dictionaryWithObject:@"" forKey:@"IP"];
    [Controller requestWithURL:ASKFORLOCATION jsondic:paramsDictionary finishBlock:^(ClassData*data) {
        if ([data.number integerValue] == 0) {
            NSDictionary *tempDictionary = [NSDictionary dictionaryWithDictionary:data.data];
            _locationModel = [LocationModel mj_objectWithKeyValues:tempDictionary];
            
            NSString *tempProvince_id =[[NSUserDefaults standardUserDefaults] objectForKey:kLocationRegion];
            //先判断是否存在之前的定位
            //如果没有就定位当前  如果已经有了  就比较之前定位和现在定位是否相同地区 不同就提示是否更换
            
            if ([TongYong isBlankObjectAndStr:tempProvince_id]) {
                
                [self.locationButton setTitle:_locationModel.province_name forState:UIControlStateNormal];
                self.locationButton.enabled = YES;
                [self loadNewData:_locationModel.province_id];
                
                [[NSUserDefaults standardUserDefaults] setObject:_locationModel.province_id forKey:kLocationRegion];
                [[NSUserDefaults standardUserDefaults] setObject:_locationModel.province_name forKey:kProvinceName];
                [[NSUserDefaults standardUserDefaults] synchronize];
            } else {
                if (![tempProvince_id isEqualToString:_locationModel.province_id]) {
                    //不等于就提示
                    //初始化AlertView
                    UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"提示"
                                                                    message:@"您当前所在的位置的分区发生了改变是否切换当前分区"
                                                                   delegate:self
                                                          cancelButtonTitle:@"取消"
                                                          otherButtonTitles:@"切换",nil];
                    
                    //这个属性继承自UIView，当一个视图中有多个AlertView时，可以用这个属性来区分
                    alert.tag = 0;
                    [alert show];
                } else {
                    [self.locationButton setTitle:_locationModel.province_name forState:UIControlStateNormal];
                    self.locationButton.enabled = YES;
                    [self loadNewData:_locationModel.province_id];
                    
                    [[NSUserDefaults standardUserDefaults] setObject:_locationModel.province_id forKey:kLocationRegion];
                    [[NSUserDefaults standardUserDefaults] setObject:_locationModel.province_name forKey:kProvinceName];
                    [[NSUserDefaults standardUserDefaults] synchronize];
                }
            }
            _regionArray = _locationModel.pro_data;
            
        } else {
            ALERTSHOW(data.message);
        }
    }];
}

#pragma mark 进入搜索界面
- (void)searchBuXiuGang {
    SearchAndResultListViewController *searchAndResultListViewController = [[SearchAndResultListViewController alloc] init];
    [self.navigationController pushViewController:searchAndResultListViewController animated:YES];
}

#pragma mark -----------------下拉刷新请求--------------------------
- (void)loadNewData:(NSString *)provinceId {
    button2.imageState=Unselect;
    button1.imageState=Select;
    
    [_tableView beginUpdates];
    
    NSDictionary *paramsDictionary = [NSDictionary dictionaryWithObject:provinceId forKey:@"province_id"];
    [Controller requestWithURL:APPHOMEAPI jsondic:paramsDictionary finishBlock:^(ClassData*data) {
        if ([data.number integerValue]==0) {
            //接收到的数据
            _allData=nil;
            _allData=data.data;
            //顶部滑动广告
            [_banner removeAllObjects];
            [_banner addObjectsFromArray:_allData[@"BANNER"]];
            
            //热门头条数据
            [_hotArray removeAllObjects];
            [_hotArray addObjectsFromArray:_allData[@"HOT"]];
            [_hotArray addObjectsFromArray:_allData[@"NEWS"]];
            
            
            [ImgAry removeAllObjects];
            for (NSInteger i=0 ; i<_banner.count; i++) {
                NSString*urlString=_banner[i][@"IMG_PATH"];
                [ImgAry addObject:urlString];
            }
            
            //将头部滑动广告赋值
            cycleScrollView.imageURLStringsGroup = ImgAry;
            
            if (typeScroll) {
                [typeScroll removeFromSuperview];
            }
            
            //控制下方两个表格的移动
            typeScroll=[[UIScrollView alloc]init];
            typeScroll.frame=CGRectMake(0, 0, width, _hotArray.count*50);
            typeScroll.contentSize=CGSizeMake(2*width, 0);
            typeScroll.pagingEnabled=YES;
            typeScroll.delegate=self;
            typeScroll.showsHorizontalScrollIndicator=NO;
            
            for (NSInteger i=0; i<2; i++) {
                
                [tableViewRe removeFromParentViewController];
                [tableViewRe.view removeFromSuperview];
                tableViewRe=nil;
                
            }
            
            //创建表格
            for (NSInteger i=0; i<2; i++) {
                
                tableViewRe=[[HomeTableVC alloc]init];
                //tableViewH.view.userInteractionEnabled=NO;
                tableViewRe.view.frame=CGRectMake(i*width, 0, width,typeScroll.frame.size.height);
                
                
                if (i == 0) {
                    tableViewRe.dataArray = _hotArray;
                    tableViewRe.isImage = NO;
                    
                }
                if (i == 1) {
                    
                    tableViewRe.isImage=YES;
                    NSMutableArray*imgDataAry=[[NSMutableArray alloc]init];
                    NSArray*array=[NSArray arrayWithArray:_allData[@"RECOMMEND"]];
                    for (NSInteger i=0; i<array.count; i++) {
                        NSDictionary*dic=array[i];
                        HeadClass*headClass=[[HeadClass alloc]initWithDic:dic];
                        [imgDataAry addObject:headClass];
                    }
                    
                    tableViewRe.dataArray=imgDataAry;
                    
                }
                
                [typeScroll addSubview:tableViewRe.view];
                [self addChildViewController:tableViewRe];
                
            }
            
            [_tableView reloadData];
            
        }
        else
        {
            ALERTSHOW(data.message);
        }
    }];
    
    // 结束刷新(相当于动画)
    [_tableView endUpdates];
    
    [_tableView.pullToRefreshView stopAnimating];
}

#pragma mark - TableView DataSource
//返回分区的个数
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return 2;
}

//返回每个分区单元格的个数
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return 1;
}

//表格要填写的内容
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (indexPath.section==0)
    {
        
        UITableViewCell*headCell=[[UITableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:nil];
        [headCell addSubview:cycleScrollView];
        return headCell;
    }
    
    
    UITableViewCell*recomCell=[[UITableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:nil];
    [recomCell addSubview:typeScroll];
    return recomCell;
    
}

#pragma mark - TableViewDelegate
//返回每行单元格的高度
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (indexPath.section==0)
    {
        return width/2.6;
    }
    if (button2.imageState==Select) {
        NSArray*ary=_allData[@"RECOMMEND"];
        typeScroll.frame=CGRectMake(0, 0, width, ary.count*(self.view.frame.size.width/3+6) );
        return ary.count*(self.view.frame.size.width/3+6);
    }
    
    NSArray*arry = _hotArray;
    typeScroll.frame=CGRectMake(0, 0,width,(arry.count-1)*46+(self.view.frame.size.width/3+6));
    return  (arry.count-1)*46+(self.view.frame.size.width/3+6);
}
//返回分区区头高度
- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
    if (section==0)
    {
        return 0;
    }
    return 50;
}

- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section {
    
    if (section==0) {
        return nil;
    }
    
    [header removeFromSuperview];
    [button1 removeFromSuperview];
    [button2 removeFromSuperview];
    [imageBtnView removeFromSuperview];
    
    header=[[UITableViewHeaderFooterView alloc]init];

    button1=[[AddImageBtn alloc]init];
    button1.frame=CGRectMake(width/4-50, 3, 100, 40);
    [button1 setTitle:@"热门头条" forState:UIControlStateNormal];
    button1.titleLabel.font=Font(15);
    [button1 addTarget:self action:@selector(change1) forControlEvents:UIControlEventTouchUpInside];
    [header addSubview:button1];
    
    button2=[[AddImageBtn alloc]init];
    button2.frame=CGRectMake(width/2+width/4-50, 3, 100, 40);
    [button2 setTitle:@"精彩推荐" forState:UIControlStateNormal];
    button2.titleLabel.font=Font(15);
    [button2 addTarget:self action:@selector(change2) forControlEvents:UIControlEventTouchUpInside];
    [header addSubview:button2];
    
    imageBtnView=[[UIImageView alloc]init];
    imageBtnView.backgroundColor=[UIColor colorWithRed:40.f/255.f green:193.f/255.f blue:226.f/255.f alpha:1];
    //UIImage*image=[UIImage imageNamed:@"bg_user_center"];
    //imageBtnView.image=image;
   //    imageBtnView.frame=CGRectMake(width/4-44, 40,88, 3);
    [header addSubview:imageBtnView];
    
    
    
//    button1.imageState=Select;
//    button2.imageState=Unselect;
    
    if (typeScroll.contentOffset.x==width||button2.imageState==Select)
    {
        button2.imageState=Select;
        button1.imageState=Unselect;
        imageBtnView.frame=CGRectMake(typeScroll.contentOffset.x/2+width/4-44+9, 35,70, 3);
        
    }else{
        imageBtnView.frame=CGRectMake(width/4-44+9, 35,70, 3);
        button1.imageState=Select;
        button2.imageState=Unselect;
    
    }

    return header;
}

#pragma mark - 图片轮播点击事件
- (void)cycleScrollView:(SDCycleScrollView *)cycleScrollView didSelectItemAtIndex:(NSInteger)index
{
    
    [MobClick event:@"banner"];
    
    //轮播图点击事件修改  根据 返回数据 TYPE:0跳转网页的链接,10:本地的跳转链接,20:现货的跳转链接
    
    NSInteger typ=[_banner[index][@"TYPE"] integerValue];
    if (typ==20) {
        NSString *st=_banner[index][@"IMG_LINK"];
        
        NSArray *array=[st componentsSeparatedByString:@"&"];
        
        NSMutableDictionary *dic=[[NSMutableDictionary alloc]init];
        for (int i=0; i<array.count; i++) {
            
            if (i==0) {
                
                [dic setObject:[[array[i] componentsSeparatedByString:@"?"][1] componentsSeparatedByString:@"="][1] forKey:[[array[i] componentsSeparatedByString:@"?"][1] componentsSeparatedByString:@"="][0]];
            }else{
                
                [dic setObject:[array[i] componentsSeparatedByString:@"="][1] forKey:[array[i] componentsSeparatedByString:@"="][0]];
            }
            
        }
        
//        UINavigationController *temp = (UINavigationController *)[super.tabBarController.viewControllers objectAtIndex:3];
//        xianhuoVC *xhvc = (xianhuoVC *)temp.topViewController;
//        xhvc.homeViewDic=dic;
//        xhvc.hometoxh=@"从首页跳转过来";
//        self.tabBarController.selectedIndex=3;
        
        RootTabBarViewController *rootTabBarViewController = [RootTabBarViewController rootViewController];
        UINavigationController *tempNavigationController=rootTabBarViewController.viewControllers[3];
        xianhuoVC *xhvc = (xianhuoVC *)tempNavigationController.topViewController;
        xhvc.homeViewDic=dic;
        xhvc.hometoxh=@"从首页跳转过来";
        [rootTabBarViewController changeRootViewControllerTo:3];
        
        
    } else {
            WebVC*webVC=[WebVC new];
            NSString*str=_banner[index][@"IMG_LINK"];
            if ([str hasPrefix:@"http"]) {
                webVC.urlString=_banner[index][@"IMG_LINK"];
                webVC.titleTxt=_banner[index][@"IMG_TITLE"];
                [self.navigationController pushViewController:webVC animated:YES];
            }
            else{
               return;
            }
    
    }
    
}

//改变按钮标题颜色
- (void)change1 {
    [self.locationImageView removeFromSuperview];
    typeScroll.contentOffset=CGPointMake(0, 0);
    imageBtnView.frame=CGRectMake(width/4-44, 40,88, 3);
    button1.imageState=Select;
    button2.imageState=Unselect;
    [_tableView reloadData];
    
}
- (void)change2 {
    [self.locationImageView removeFromSuperview];
    typeScroll.contentOffset=CGPointMake(width, 0);
    button2.imageState=Select;
    button1.imageState=Unselect;
    imageBtnView.frame=CGRectMake(width/2+width/4-44, 40,88, 3);
    [_tableView reloadData];
    
}

//表格的协议方法
- (void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView {
    [self.locationImageView removeFromSuperview];
    if (typeScroll.contentOffset.x==0)
    {
        imageBtnView.frame=CGRectMake(width/4-44, 40,88, 3);
        button1.imageState=Select;
        button2.imageState=Unselect;
        
    }
    if (typeScroll.contentOffset.x==width)
    {
        button2.imageState=Select;
        button1.imageState=Unselect;
        imageBtnView.frame=CGRectMake(typeScroll.contentOffset.x/2+width/4-44, 40,88, 3);
        
    }
    [_tableView reloadData];
}

- (void)addImgBtn {
    //视图View
    UIView*view=[[UIView alloc]init];
    view.backgroundColor=bgVCcolor;
    view.frame=CGRectMake(0, 60, width, height-109);
    [self.view addSubview:view];
    //按钮
    UIButton*button=[UIButton buttonWithType:UIButtonTypeCustom];
    button.layer.masksToBounds=YES;
    button.titleLabel.font=[UIFont systemFontOfSize:15];
    [button setBackgroundImage:[UIImage imageNamed:@"ic_load_error"] forState:UIControlStateNormal];
    [button addTarget:self action:@selector(clickUpData) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:button];
    [button mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerY.equalTo(self.view.mas_centerY).offset(0);
        make.centerX.equalTo(self.view.mas_centerX).offset(0);
        make.height.offset(100);  make.width.offset(130);
    }];
    //标签
    UILabel*label=[[UILabel alloc]init];
    label.textColor=[UIColor grayColor];
    label.text=@"点击此处重新加载";  label.font=[UIFont systemFontOfSize:15];
    label.textAlignment=NSTextAlignmentCenter;
    label.textColor=[UIColor blackColor];
    [self.view addSubview:label];
    [label mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(button.mas_bottom).offset(5);
        make.height.offset(20);  make.centerX.equalTo(self.view.mas_centerX).offset(0);
    }];
}

- (void)clickUpData {
    //刷新数据
//    [self  insertRowAtTop];
}

#pragma mark - lazyLoad
- (UIImageView *)locationImageView {
    if (!_locationImageView) {
        _locationImageView = [[UIImageView alloc] init];
        _locationImageView.image = [UIImage imageNamed:@"Image_location.png"];
        _locationImageView.alpha = 1;
        _locationImageView.userInteractionEnabled = YES;
        _locationImageView.bounds = CGRectMake(0, 0, 100, 30*_regionArray.count);
        
        // 添加全国地区按钮
        for (int i = 0; i < _regionArray.count; i++) {
            ProvinceModel *provinceModel = _regionArray[i];
            RegionButton *countryButton = [RegionButton buttonWithType:UIButtonTypeCustom];
            countryButton.provinceModel = provinceModel;
            [countryButton setTitle:provinceModel.province_name forState:UIControlStateNormal];
            countryButton.titleLabel.font = Font(12);
            countryButton.titleLabel.textAlignment=NSTextAlignmentCenter;
            countryButton.frame = CGRectMake(0, 30*i, _locationImageView.width, 30);
            [countryButton addTarget:self action:@selector(countryButtonOnClick:) forControlEvents:UIControlEventTouchUpInside];
            [_locationImageView addSubview:countryButton];
            [_regionButtonArray addObject:countryButton];
            
            // 区别两种字体颜色
            if ([self.locationButton.titleLabel.text isEqualToString:provinceModel.province_name]) {
                [countryButton setTitleColor:RGBCOLOR(90, 191, 219) forState:UIControlStateNormal];
            } else {
                [countryButton setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
            }
            
            if (i != _regionArray.count-1) {
                // 灰色的分割线
                UIView *lineView = [[UIView alloc] initWithFrame:CGRectMake(0, countryButton.bottom, _locationImageView.width, 1)];
                lineView.backgroundColor = [UIColor lightGrayColor];
                [_locationImageView addSubview:lineView];
            }
        }
    }
    return _locationImageView;
}

#pragma mark - 定位按钮点击事件
- (void)countryButtonOnClick:(id)sender {
    [self.locationImageView removeFromSuperview];
    RegionButton *tempRegionButton = (RegionButton *)sender;
    
    [[NSUserDefaults standardUserDefaults] setObject:tempRegionButton.provinceModel.province_id forKey:kLocationRegion];
    [[NSUserDefaults standardUserDefaults] setObject:tempRegionButton.provinceModel.province_name forKey:kProvinceName];
    [[NSUserDefaults standardUserDefaults] synchronize];
    
    if (![self.locationButton.titleLabel.text isEqualToString:tempRegionButton.provinceModel.province_name]) {
        // 通知现货列表界面刷新界面
        [[NSNotificationCenter defaultCenter] postNotificationName:kChangedLocationNotification object:nil];
    }
    
    [self.locationButton setTitle:tempRegionButton.provinceModel.province_name forState:UIControlStateNormal];
    
    // 重新加载界面
    [self loadNewData:tempRegionButton.provinceModel.province_id];
}

- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event {
    [self.locationImageView removeFromSuperview];
}
//根据被点击按钮的索引处理点击事件
- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex {
    if (alertView.tag==0) {
        if (buttonIndex==1) {
            //切换
            
            [self.locationButton setTitle:_locationModel.province_name forState:UIControlStateNormal];
            self.locationButton.enabled = YES;
            [self loadNewData:_locationModel.province_id];
            [[NSUserDefaults standardUserDefaults] setObject:_locationModel.province_id forKey:kLocationRegion];
            [[NSUserDefaults standardUserDefaults] setObject:_locationModel.province_name forKey:kProvinceName];
            [[NSUserDefaults standardUserDefaults] synchronize];
            
        }else if(buttonIndex==0){
            //否 不切换
            
             NSString *tempProvince_id =[[NSUserDefaults standardUserDefaults] objectForKey:kLocationRegion];
             NSString *tempProvince_name =[[NSUserDefaults standardUserDefaults] objectForKey:kProvinceName];
            
            [self.locationButton setTitle:tempProvince_name forState:UIControlStateNormal];
            self.locationButton.enabled = YES;
            [self loadNewData:tempProvince_id];
            
            
        }

    }
}
@end
